﻿<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> 
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> 
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %> 
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ResourceGantUserControl.ascx.cs" Inherits="PepsiCo.RBS.WebParts.ResourceGant.ResourceGantUserControl" %>

<script src="/_layouts/PepsiCo.RBS/dhtmlxgantt.js" type="text/javascript"></script>
<link href="/_layouts/PepsiCo.RBS/dhtmlxgantt.css" rel="stylesheet" type="text/css" />
<script src="/_layouts/PepsiCo.RBS/jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="/_layouts/PepsiCo.RBS/jquery.SPServices-0.7.2.min.js" type="text/javascript"></script>
<link href="/_layouts/PepsiCo.RBS/dhtmlxcalendar.css" rel="stylesheet" type="text/css" />
<link href="/_layouts/PepsiCo.RBS/skins/dhtmlxcalendar_dhx_skyblue.css" rel="stylesheet" type="text/css" />
<script src="/_layouts/PepsiCo.RBS/dhtmlxcalendar.js" type="text/javascript"></script>
<script src="/_layouts/PepsiCo.RBS/moment.min.js" type="text/javascript"></script>

<script type="text/javascript">
     /*
     var myCalendar;
     function doOnLoad() {
     myCalendar = new dhtmlXCalendarObject(["date_from", "date_to"]);
     myCalendar.setDate("2013-03-10");
     myCalendar.hideTime();
     // init values
     var t = new Date();
     byId("date_from").value = "2013-03-05";
     byId("date_to").value = "2013-03-15";
     }

     function setSens(id, k) {
     // update range
     if (k == "min") {
     myCalendar.setSensitiveRange(byId(id).value, null);
     } else {
     myCalendar.setSensitiveRange(null, byId(id).value);
     }
     }

     function byId(id) {
     return document.getElementById(id);
     }*/

     var myCalendar;
     function doOnLoad() {
         myCalendar = new dhtmlXCalendarObject({
             input: "calendar_input",
             button: "calendar_icon"
         });
         myCalendar.hideTime();
         myCalendar.setDateFormat("%m/%d/%Y");
         var defaultDay = new Date();
         myCalendar.setDate(defaultDay);

         /*
         myCalendar.attachEvent("onClick", function (side, d) {
             myCalendar.getFormatedDate(null, d);
             return;
         });

         myCalendar.attachEvent("onBeforeChange", function (side, d) {
             myCalendar.getFormatedDate(null, d);
             return;
         });
         */
     }

</script>

<div>
    <!--
    <span class="label">From:</span> <input type="text" id="date_from" onclick="setSens('date_to', 'max');" readonly="true" />
    &nbsp;&nbsp;
    <span class="label">To:</span> <input type="text" id="date_to" onclick="setSens('date_from', 'min');" readonly="true" />
    -->

    <span>Check date:</span>
    <input type="text" id="calendar_input" style="width: 70px;" readonly="readonly" />
    <img id="calendar_icon" src="/_layouts/PepsiCo.RBS/calendar.gif" alt="" style="cursor:pointer;" border="0" />
    &nbsp;&nbsp;&nbsp;&nbsp;
    <div style="display: none;">
        <span>Choose type:</span>
        <input id="radioDay" type="radio" value="Today" checked="checked" name="GantType" />Date
        <input id="radioWeek" type="radio" value="Week" name="GantType" />Week
        <input id="radioMonth" type="radio" value="Month" name="GantType" />Month
    </div>
</div>

<br />

<div id="gantt_here" style="width: 100%; height: 400px;">
</div>



<script type="text/javascript">
    var MEETINGROOMS = {};
    var RESOURCES = {};
    var PEPSIRESOURCES = {data:[]};
    //var jsonData = "{-1} id: {0}, pepsico: '{1}', start_date: '{2}', duration: {3}, open: true, parent: {4} {-2}";
    //var startDate = "{0}-{1}-{2}T00:00:00Z";

    //Grant config one day
    function ConfigGant(calDate) {
        //Date
        /*
        gantt.start_date = new Date(2013, 11, 23, 8, 0, 0); //new Date(calDate.getFullYear(), calDate.getMonth(), calDate.getDate(), 8, 0, 0); //2013, 10, 4, 7, 30
        //alert(gantt.config.start_date);
        gantt.end_date = new Date(2013, 11, 23, 22, 0, 0); // new Date(calDate.getFullYear(), calDate.getMonth(), calDate.getDate(), 22, 0, 0); //2013, 10, 4, 19, 30
        //alert(gantt.config.end_date);
        //gantt.config.date_grid = "%d %M";
        gantt.config.start_date = new Date(2013, 11, 23, 8, 0, 0);
        gantt.config.end_date = new Date(2013, 11, 23, 22, 0, 0);
        gantt.config.scale_unit = "hour"; //"minute";
        gantt.config.time_step= 1;
        gantt.config.duration_unit = 60 * 60 * 1000;
        gantt.config.date_scale = "%H:%i";
        gantt.config.subscales = [
		    { unit: "minute", step: 30, date: "%i" }
	    ];
        */
        //var calDateMoment = moment(calDate);

        //gantt.start_date = new Date(2013, 10, 23, 8, 0, 0);
        //gantt.end_date = new Date(2013, 10, 23, 22, 0, 0);
        //gantt.config.start_date = new Date(2013, 10, 23, 8, 0, 0);
        //gantt.config.end_date = new Date(2013, 10, 23, 22, 0, 0);

        gantt.config.scale_unit = "day";
        gantt.config.step = 1;
        gantt.config.date_scale = "%d %M";
        gantt.config.duration_unit = 60 * 60 * 1000;
        gantt.config.scale_height = 27;
        gantt.templates.date_scale = null;
        gantt.config.subscales = [
            { unit: "hour", step: 1, date: "%H"},
		    { unit: "minute", step: 15, date: "%i" }
	    ];
        gantt.config.scale_height = 50;
        gantt.config.scale_width = 10;

        gantt.templates.task_class = function (start, end, task) {
            return "meetingroom" + task.meetingroom;
        };


        // Month Work fine
        /* 
        //gantt.config.start_date = new Date(calDate.getFullYear(), calDate.getMonth(), 1); //2013, 10, 4, 7, 30
        //alert(gantt.config.start_date);
        //gantt.config.end_date = new Date(calDate.getFullYear(), calDate.getMonth(), 30); //2013, 10, 4, 19, 30
        //alert(gantt.config.end_date);
        gantt.config.scale_unit = "month";
        gantt.config.step = 1;
        gantt.config.date_scale = "%F, %Y";
        gantt.config.min_column_width = 50;

        gantt.config.scale_height = 90;

        var weekScaleTemplate = function (date) {
            var dateToStr = gantt.date.date_to_str("%d %M");
            var endDate = gantt.date.add(gantt.date.add(date, 1, "week"), -1, "day");
            return dateToStr(date) + " - " + dateToStr(endDate);
        };

        gantt.config.subscales = [
		{ unit: "week", step: 1, template: weekScaleTemplate },
		{ unit: "day", step: 1, date: "%D" }
        ];
        */

        // Week Work fine
        /*
        var weekScaleTemplate = function(date){
					var dateToStr = gantt.date.date_to_str("%d %M");
					var endDate = gantt.date.add(gantt.date.add(date, 1, "week"), -1, "day");
					return dateToStr(date) + " - " + dateToStr(endDate);
				};

		gantt.config.scale_unit = "week";
		gantt.config.step = 1;
		gantt.templates.date_scale = weekScaleTemplate;
		gantt.config.subscales = [
			{ unit: "day", step: 1, date: "%D" },
            { unit: "hour", step: 1, date: "%H" }
		];
		gantt.config.scale_height = 50;
        */
    }

    //Get list rooms -> dictionary
    function GetMeetingRooms() {
        $().SPServices({
            operation: "GetListItems",
            async: false,
            webURL: $().SPServices.SPGetCurrentSite(),
            listName: "Meeting Rooms",
            CAMLQuery: "<Query><Where><Eq><FieldRef Name='IsActive' /><Value Type='Boolean'>1</Value></Eq></Where></Query>",
            CAMLViewFields: "<ViewFields><FieldRef Name='Title' /><FieldRef Name='Color' /></ViewFields>",
            completefunc: function (xData, Status) {
                $(xData.responseXML).SPFilterNode("z:row").each(function () {
                    MEETINGROOMS[$(this).attr("ows_ID")] = $(this).attr("ows_Color") + "|||" + $(this).attr("ows_Title");
                    //alert(MEETINGROOMS[(this).attr("ows_ID")]);
                });
            }
        });
    }

    //Get list resources -> dictionary
    function GetResources() {
        $().SPServices({
            operation: "GetListItems",
            async: false,
            webURL: $().SPServices.SPGetCurrentSite(),
            listName: "Resources",
            CAMLQuery: "<Query><Where><And><Eq><FieldRef Name='IsActive' /><Value Type='Boolean'>1</Value></Eq><Eq><FieldRef Name='IsPrivate' /><Value Type='Boolean'>0</Value></Eq></And></Where></Query>",
            CAMLViewFields: "<ViewFields><FieldRef Name='Title' /></ViewFields>",
            completefunc: function (xData, Status) {
                $(xData.responseXML).SPFilterNode("z:row").each(function () {
                    RESOURCES[$(this).attr("ows_ID")] = $(this).attr("ows_Title");
                    //alert(RESOURCES[(this).attr("ows_ID")]);
                });
            }
        });
    }

    //Get events
    function GetMeetingEvents(startDate, type) {
        //var startDate = "2013-11-21T00:00:00Z";
        var count = 3, meetingRoomParent = 1, resourceParent = 2, addMeetingRoomParent = false, addResourceParent = false;
        //var PEPSIRESOURCES = { data: [
        //    { id: meetingRoomParent, pepsico: "Meeting rooms", start_date: "", duration: 0, open: true },
        //    { id: resourceParent, pepsico: "Resources", start_date: "", duration: 0, open: true }
        //] };
        PEPSIRESOURCES = { data: [] };
        gantt.clearAll();

        $().SPServices({
            operation: "GetListItems",
            async: false,
            listName: "Book Events",
            CAMLViewFields: "<ViewFields>" +
                "<FieldRef Name='Title' />" +
                "<FieldRef Name='EventDate' />" +
                "<FieldRef Name='EndDate' />" +
                "<FieldRef Name='Location' />" +
			    "<FieldRef Name='ResourceRequest' />" +
			    "<FieldRef Name='MeetingRoom' />" +
                "<FieldRef Name='Description' />" +
                "<FieldRef Name='fRecurrence' />" +
                "<FieldRef Name='RecurrenceData' />" +
            "</ViewFields>",
            CAMLQuery: "<Query>" +
                "<Where>" +
                    "<DateRangesOverlap>" +
                        "<FieldRef Name='EventDate' />" +
                        "<FieldRef Name='EndDate' />" +
                        "<FieldRef Name='RecurrenceID' />" +
                        "<Value Type='DateTime'>" +
                            "<" + type + "/>" + //"<Today />" +
                        "</Value>" +
                    "</DateRangesOverlap>" +
                "</Where>" +
                "<OrderBy>" +
                    "<FieldRef Name='EventDate' />" +
                "</OrderBy>" +
            "</Query>",
            CAMLQueryOptions: "<QueryOptions>" +
                "<CalendarDate>" + startDate + "</CalendarDate>" +
                "<RecurrencePatternXMLVersion>v3</RecurrencePatternXMLVersion>" +
                "<ExpandRecurrence>TRUE</ExpandRecurrence>" +
            "</QueryOptions>",
            completefunc: function (xData, Status) {
                $(xData.responseXML).SPFilterNode("z:row").each(function () {
                    /*                
                    var $node = $(this),
                    fADE = $node.attr("ows_fAllDayEvent") || 0,
                    thisADE = (fADE == 0),
                    thisID = $node.attr("ows_ID"),
                    sepID = thisID.indexOf(';#'),
                    thisTitle = $node.attr("ows_Title"),
                    thisRecurrence = $node.attr("ows_fRecurrence"),
                    thisDesc = $node.attr("ows_Description");
                    if (sepID != -1) thisID = thisID.substring(0, sepID);
                    var thisUrl = "DispForm.aspx?ID=" + thisID,
                    thisClass = thisTitle.replace(" ", "").substr(0, 10).replace(",", "").replace(" ", "") + thisID,
                    thisRD = $node.attr("ows_RecurrenceData");
                    */
                    //if ($.isEmptyObject($(this).attr("ows_MeetingRoom"))) {
                    //    PEPSIRESOURCES.data.push({ id: count, pepsico: $(this).attr("ows_Title"), start_date: '04-11-2013 08:00', duration: 4, parent: 2, open: true });
                    //}

                    var owsStartDate = $(this).attr("ows_EventDate");
                    var owsEndDate = $(this).attr("ows_EndDate");

                    var startDateValue = moment(owsStartDate);
                    var endDateValue = moment(owsEndDate);

                    //alert(startDateValue.format("DD-MM-YYYY hh:mm"));
                    //alert(endDateValue);

                    //Cal duration
                    //var startArray = owsStartDate.split(' '), endArray = owsEndDate.split(' ');
                    //var startYearMonthDateArray = startArray[0].split('-'), startHourMinuteSecondArray = startArray[1].split(':');
                    //var endYearMonthDateArray = endArray[0].split('-'), endHourMinuteSecondArray = endArray[1].split(':');

                    //var startValue = new Date(startYearMonthDateArray[0], (startYearMonthDateArray[1] - 1), startYearMonthDateArray[2], startHourMinuteSecondArray[0], startHourMinuteSecondArray[1], startHourMinuteSecondArray[2]);
                    //var endValue = new Date(endYearMonthDateArray[0], (endYearMonthDateArray[1] - 1), endYearMonthDateArray[2], endHourMinuteSecondArray[0], endHourMinuteSecondArray[1], endHourMinuteSecondArray[2]);

                    //var owsStartDateValue = startYearMonthDateArray[2].toString() + "-" + startYearMonthDateArray[1].toString() + "-" + startYearMonthDateArray[0].toString() + " " + startArray[1].toString() + "'";
                    //alert(owsStartDateValue);

                    var owsDuration = (endDateValue - startDateValue) / (gantt.config.duration_unit);
                    //alert(owsDuration);

                    var meetingRoomID = 0;
                    var owsMeetingRoom = $(this).attr("ows_MeetingRoom");
                    if (!($.isEmptyObject(owsMeetingRoom))) {
                        if (!addMeetingRoomParent) {
                            PEPSIRESOURCES.data.push({ id: meetingRoomParent, text: "Meeting rooms", starthour: '', endhour: '', owner: '', start_date: '', duration: 0, open: true });
                        }
                        var meetingRoomArray = owsMeetingRoom.split(';#');
                        meetingRoomID = meetingRoomArray[0];
                        PEPSIRESOURCES.data.push({ id: count, text: meetingRoomArray[1], starthour: startDateValue.format("hh:mm"), endhour: endDateValue.format("hh:mm"), owner: $(this).attr("ows_User").split(';#')[1], start_date: startDateValue, duration: owsDuration, parent: meetingRoomParent, meetingroom: meetingRoomID });
                        count++;
                    }

                    var owsResourceRequest = $(this).attr("ows_ResourceRequest");
                    if (!($.isEmptyObject(owsResourceRequest))) {
                        if (!addResourceParent) {
                            PEPSIRESOURCES.data.push({ id: resourceParent, text: "Resources", starthour: '', endhour: '', owner: '', start_date: '', duration: 0, open: true });
                        }
                        var resourceArray = owsResourceRequest.split(';#');
                        for (var i = 0; i < resourceArray.length; i++) {
                            if ((i % 2) != 0) {
                                PEPSIRESOURCES.data.push({ id: count, text: resourceArray[i], starthour: startDateValue.format("hh:mm"), endhour: endDateValue.format("hh:mm"), owner: $(this).attr("ows_User").split(';#')[1], start_date: startDateValue, duration: owsDuration, parent: resourceParent, meetingroom: meetingRoomID });
                                count++;
                            }
                        }
                    }

                });
            }
        });
    }

    function AddMeetingRoomClass() {
        var meetingRoomCssFormat = ".meetingroom{0} {-1} background: {1}; {-2}";
        var meetingRoomCss = "";
        $().SPServices({
            operation: "GetListItems",
            async: false,
            webURL: $().SPServices.SPGetCurrentSite(),
            listName: "Meeting Rooms",
            CAMLQuery: "<Query><Where><Eq><FieldRef Name='IsActive' /><Value Type='Boolean'>1</Value></Eq></Where></Query>",
            CAMLViewFields: "<ViewFields><FieldRef Name='Title' /><FieldRef Name='Color' /></ViewFields>",
            completefunc: function (xData, Status) {
                $(xData.responseXML).SPFilterNode("z:row").each(function () {
                    meetingRoomCssFormat.format([$(this).attr("ows_ID"), $(this).attr("ows_Color")]);
                    meetingRoomCss += meetingRoomCssFormat.format([$(this).attr("ows_ID"), $(this).attr("ows_Color")]);
                });
            }
        });
        meetingRoomCss = "<style>" + meetingRoomCss + "</style>";
        $(meetingRoomCss).appendTo('body');
    }


    String.prototype.format = function (args) {
        var str = this;
        return str.replace(String.prototype.format.regex, function (item) {
            var intVal = parseInt(item.substring(1, item.length - 1));
            var replace;
            if (intVal >= 0) {
                replace = args[intVal];
            } else if (intVal === -1) {
                replace = "{";
            } else if (intVal === -2) {
                replace = "}";
            } else {
                replace = "";
            }
            return replace;
        });
    };
    String.prototype.format.regex = new RegExp("{-?[0-9]+}", "g");


    gantt.config.columns = [
                { name: "text", label: "Resources", align: "left", tree: true, width: '150' },
                { name: "starthour", label: "Start", align: "center", width: '30' },
                { name: "endhour", label: "End", align: "center", width: '30' },
                { name: "owner", label: "Owner", align: "center", width: '70' }
                ];

    gantt.config.drag_move = false;
    gantt.config.details_on_dblclick = false;
    gantt.config.drag_lightbox = false;
    gantt.config.drag_links = false;
    gantt.config.details_on_create = false;
    gantt.config.readonly = true;
    gantt.config.min_column_width = 20;
    gantt.init("gantt_here");

    function ShowGant(calDate, calType) {

        //Config gant day -> Today
        ConfigGant(calDate);
        var startDateString = moment(calDate).format("YYYY-MM-DD HH:mm:ss Z");
        //alert(startDateString);
        GetMeetingEvents(startDateString, calType);
        gantt.parse(PEPSIRESOURCES);
        
    }

    $(document).ready(function () {
        //Load calendar
        doOnLoad();
        //Load css class
        AddMeetingRoomClass();
        //Frist load
        var currentDate = new moment(new Date());
        $("#calendar_input").val(currentDate.format("DD/MM/YYYY"));
        ShowGant(currentDate.format("YYYY-MM-DD"), "Today");

        //Attach to event
        myCalendar.attachEvent("onClick", function (date) {
            //console.log(date);
            //alert("Year: " + date.getFullYear() + " - Month: " + date.getMonth() + " - Day: " + date.getDate());
            //ConfigGantOneDay(date);
            //var startDateString = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + "T00:00:00Z";
            ShowGant(date, "Today");
        });

    });

</script>